package com.poisonh.unifiedauth.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import com.lzy.okhttputils.model.HttpParams;
import com.poisonh.unifiedauth.R;
import com.poisonh.unifiedauth.ui.svprogresshud.SVProgressHUD;
import com.poisonh.unifiedauth.utils.ActivityStack;
import com.poisonh.unifiedauth.utils.CommonUtils;
import com.poisonh.unifiedauth.utils.ConstantUitls;
import com.poisonh.unifiedauth.utils.MyHttpsUtils;
import com.poisonh.unifiedauth.utils.PreferencesUtils;
import com.poisonh.unifiedauth.utils.ToastUtils;
import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;

//import com.poisonh.unifiedauth.jpush.SMSContentObserver;

/**
 * 登录/注册Activity
 * Created by PoisonH on 2016/6/21.
 */
public class LoginActivity extends AppCompatActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener
{
    //手机号输入框
    private EditText mEditTextPhone;
    //验证码输入框
    private EditText mEditTextPhoneCode;
    //登录按钮
    private Button mBtnLogin;
    //发送验证码按钮
    private Button mBtnSendPhoneCode;
    //同意协议按钮
    private CheckBox mCheckBoxAgreement;
    //手机号码
    private String mStrPhone;
    //验证码
    private String mStrPhoneCode;
    //同意协议文字
    private TextView mTvAgreement;
    //短信观察者
//    private SMSContentObserver smsContentObserver;
    //验证码是否输入了6位
    private boolean code6bit = false;
    //手机号是否输入了11位
    private boolean phone11bit = false;
    //是否同意了协议
    private boolean isagreen = false;

    // 要申请的权限
    private String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private AlertDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

//        smsContentObserver = new SMSContentObserver(this, handler);
        //注册短信观察者
//        this.getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, smsContentObserver);
        initView();

        // 版本判断。当手机系统大于 23 时，才有必要去判断权限是否获取
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            // 检查该权限是否已经获取
            int i = ContextCompat.checkSelfPermission(this, permissions[0]);
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            if (i != PackageManager.PERMISSION_GRANTED) {
                // 如果没有授予该权限，就去提示用户请求
               // showDialogTipUserRequestPermission();
                startRequestPermission();
            }

        }
    }

    //初始化布局
    private void initView()
    {
        mEditTextPhone = (EditText) findViewById(R.id.login_input_phone);
        mEditTextPhoneCode = (EditText) findViewById(R.id.login_input_phonecode);
        mBtnLogin = (Button) findViewById(R.id.btn_login);
        mBtnSendPhoneCode = (Button) findViewById(R.id.btn_send_phonecode);
        mCheckBoxAgreement = (CheckBox) findViewById(R.id.cb_box);
        mCheckBoxAgreement.setOnCheckedChangeListener(this);
        mBtnLogin.setOnClickListener(this);
        mBtnSendPhoneCode.setOnClickListener(this);
        mEditTextPhone.addTextChangedListener(mEditTextPhoneWatcher);
        mEditTextPhoneCode.addTextChangedListener(mEditTextCodeWatcher);
        mTvAgreement = (TextView) findViewById(R.id.tv_agreement);
        mTvAgreement.setOnClickListener(this);

    }

    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.btn_send_phonecode:
                mStrPhone = mEditTextPhone.getText().toString();
                //判断是否是手机号
                if (mStrPhone.trim().length() != 11)
                {
                    ToastUtils.showToast(LoginActivity.this, getString(R.string.sure_input_11_phone));
                } else
                {
                    SVProgressHUD.showWithStatus(this, "加载中...");
                    senSmsCode(mStrPhone);
                    mBtnSendPhoneCode.setEnabled(false);
                }
                break;

            case R.id.btn_login:
                mStrPhone = mEditTextPhone.getText().toString();
                mStrPhoneCode = mEditTextPhoneCode.getText().toString();
                if (mStrPhoneCode.isEmpty() || mStrPhone.trim().length() != 11)
                {
                    ToastUtils.showToast(LoginActivity.this, "请确认手机号或验证码正确");
                } else
                {
                    if (!mCheckBoxAgreement.isChecked())
                    {
                        ToastUtils.showToast(LoginActivity.this, "请阅读相关协议");
                    } else
                    {

                        SVProgressHUD.showWithStatus(this, "加载中...");
                        login();
                    }
                }
                break;
            case R.id.tv_agreement:
                Intent intent = new Intent(LoginActivity.this, ServiceListActvity.class);
                intent.putExtra("TITLE", "用户协议");
                startActivity(intent);
                break;
        }
    }

    TextWatcher mEditTextPhoneWatcher = new TextWatcher()
    {
        private CharSequence temp;

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after)
        {
            temp = s;
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count)
        {
        }

        @Override
        public void afterTextChanged(Editable s)
        {
            if (temp.length() == 11)
            {
                phone11bit = true;
                changeBtnLoginState();
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(mEditTextPhone.getWindowToken(), 0);
            } else
            {
                phone11bit = false;
                changeBtnLoginState();
            }
        }
    };

    TextWatcher mEditTextCodeWatcher = new TextWatcher()
    {
        private CharSequence temp;

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after)
        {
            temp = s;
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count)
        {
        }

        @Override
        public void afterTextChanged(Editable s)
        {
            if (temp.length() == 6)
            {
                code6bit = true;
                changeBtnLoginState();
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(mEditTextPhoneCode.getWindowToken(), 0);
            } else
            {
                code6bit = false;
                changeBtnLoginState();
            }
        }
    };

    /**
     * 发送短信验证码
     */
    private void senSmsCode(String mStrPhone)
    {
        HttpParams params = new HttpParams();
        params.put("phone", mStrPhone);
        MyHttpsUtils.post(ConstantUitls.REQUEDT_URL + ConstantUitls.SEND_MESSAGE, params, new MyHttpsUtils.ResultCallback()
        {
            @Override
            public void onSuccess(String response)
            {

                CommonUtils.CountdownTime(mBtnSendPhoneCode);
                SVProgressHUD.dismiss(LoginActivity.this);
                //  ToastUtils.showToast(LoginActivity.this, getString(R.string.send_code_success));
            }

            @Override
            public void onFailure(String failReason)
            {
                ToastUtils.showToast(LoginActivity.this, failReason);
                mBtnSendPhoneCode.setText(R.string.login_tips_btn_phonecode);
                mBtnSendPhoneCode.setEnabled(true);
                SVProgressHUD.dismiss(LoginActivity.this);
            }
        });
    }

    /**
     * 登录
     */
    private void login()
    {
        HttpParams params = new HttpParams();
        params.put("phone", mStrPhone);
        params.put("msgCode", mStrPhoneCode);
        params.put("verifyType", "0");
        MyHttpsUtils.post(ConstantUitls.REQUEDT_URL + ConstantUitls.VERIFY_RAND_NUMCODE, params, new MyHttpsUtils.ResultCallback()
        {
            @Override
            public void onSuccess(String response)
            {
                checkResult(response);
                SVProgressHUD.dismiss(LoginActivity.this);
            }

            @Override
            public void onFailure(String failReason)
            {
                ToastUtils.showToast(LoginActivity.this, "登录失败,请确认验证码是否正确");
                SVProgressHUD.dismiss(LoginActivity.this);
            }
        });
    }

    /**
     * 解析json数据，根据返回值判断是否注册
     *
     * @param response
     */
    private void checkResult(String response)
    {
        try
        {
            JSONObject mjson = new JSONObject(response);
            JSONObject mjson2 = mjson.getJSONObject("results");
            String mStrResult = mjson2.getString("type");
            Intent mIntent = new Intent(LoginActivity.this, SettingPinCodeActivity.class);

            if (mStrResult.equals("Error"))
            {
                ToastUtils.showToast(LoginActivity.this, "未知错误");
                return;
            } else if (mStrResult.equals("Login"))
            {
                //登录
                ConstantUitls.TYPE = 1;
                String mId = mjson2.getString("userId");
                PreferencesUtils.putString(LoginActivity.this, "ID", mId);

            } else if (mStrResult.equals("Registry"))
            {
                //注册
                ConstantUitls.TYPE = 0;
            }
            PreferencesUtils.putString(LoginActivity.this, "PHONE", mStrPhone);
            startActivity(mIntent);
            finish();
        } catch (JSONException e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 根据手机号、验证码、同意协议改变登录按钮状态
     */
    private void changeBtnLoginState()
    {
        if (code6bit && phone11bit && isagreen)
        {
            mBtnLogin.setEnabled(true);
            mBtnLogin.setTextColor(getResources().getColor(R.color.btn_seleted_true));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                mBtnLogin.setBackground(getResources().getDrawable(R.drawable.shape_login_btn_normal));
            }else {
                mBtnLogin.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_login_btn_normal));
            }
        } else
        {
            mBtnLogin.setEnabled(false);
            mBtnLogin.setTextColor(getResources().getColor(R.color.btn_seleted_flase));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                mBtnLogin.setBackground(getResources().getDrawable(R.drawable.shape_login_btn_abnormal));
            }else {
                mBtnLogin.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_login_btn_abnormal));
            }
        }
    }

    @Override
    protected void onResume()
    {
        super.onResume();
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK && ConstantUitls.TYPE == 5)
        {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            if (msg.what == 1)
            {
                mEditTextPhoneCode.setText("");
                mEditTextPhoneCode.setText(msg.obj.toString());
            }
        }
    };

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        ActivityStack.getAppManager().finishActivity(this);
//        this.getContentResolver().unregisterContentObserver(smsContentObserver);
        handler = null;
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
    {
        if (isChecked)
        {
            isagreen = true;
            changeBtnLoginState();
        } else
        {
            isagreen = false;
            changeBtnLoginState();
        }
    }



//        // 提示用户该请求权限的弹出框
//        private void showDialogTipUserRequestPermission() {
////            .setTitle("存储权限不可用")
////                    .setMessage("由于支付宝需要获取存储空间，为你存储个人信息；否则，您将无法正常使用支付宝")
////                    .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
//            new AlertDialog.Builder(this)
//                    .setTitle("存储权限不可用")
//                    .setMessage("由于年轮认证需要获取存储空间，为你存储个人信息;否则，您将无法正常使用年轮")
//                    .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            startRequestPermission();
//                        }
//                    })
//                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            finish();
//                        }
//                    }).setCancelable(false).show();
//        }

        // 开始提交请求权限
        private void startRequestPermission() {
            ActivityCompat.requestPermissions(this, permissions, 321);
        }

        // 用户权限 申请 的回调方法
        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);

            if (requestCode == 321) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {//表示权限获取失败
                        // 判断用户是否 点击了不再提醒。(检测该权限是否还可以申请)
                        boolean b = shouldShowRequestPermissionRationale(permissions[0]);
                        if (!b) {
                            // 用户还是想用我的 APP 的
                            // 提示用户去应用设置界面手动开启权限
                            showDialogTipUserGoToAppSettting();
                        } else
                            finish();
                    } else {
                        Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }

        // 提示用户去应用设置界面手动开启权限

        private void showDialogTipUserGoToAppSettting() {

            dialog = new AlertDialog.Builder(this)
                    .setTitle("存储权限不可用")
                    .setMessage("请在-应用设置-权限-中，允许年轮使用存储权限来保存用户数据;否则，您将无法正常使用年轮")
                    .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // 跳转到应用设置界面
                            goToAppSetting();
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    }).setCancelable(false).show();
        }

        // 跳转到当前应用的设置界面
        private void goToAppSetting() {
            Intent intent = new Intent();

            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            Uri uri = Uri.fromParts("package", getPackageName(), null);
            intent.setData(uri);

            startActivityForResult(intent, 123);
        }

        //
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == 123) {//接收权限设置的消息
                if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    // 检查该权限是否已经获取
                    int i = ContextCompat.checkSelfPermission(this, permissions[0]);
                    // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                    if (i != PackageManager.PERMISSION_GRANTED) {
                        // 提示用户应该去应用设置界面手动开启权限
                        showDialogTipUserGoToAppSettting();
                       // Settings.System.canWrite(this);
                    } else {
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                        }
                        Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }

































}
